package cn.iocoder.yudao.module.carbon.controller.admin.emissionfactor;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.carbon.controller.admin.emissionfactor.vo.*;
import cn.iocoder.yudao.module.carbon.convert.emissionfactor.EmissionFactorConvert;
import cn.iocoder.yudao.module.carbon.dal.dataobject.emissionfactor.EmissionFactorDO;
import cn.iocoder.yudao.module.carbon.service.emissionfactor.EmissionFactorService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Tag(name =  "管理后台 - 碳排放因子")
@RestController
@RequestMapping("/carbon/emission-factor")
@Validated
public class EmissionFactorController {

    @Resource
    private EmissionFactorService emissionFactorService;

    @PostMapping("/create")
    @Operation(summary = "创建碳排放因子")
    @PreAuthorize("@ss.hasPermission('carbon:emission-factor:create')")
    public CommonResult<Integer> createEmissionFactor(@Valid @RequestBody EmissionFactorCreateReqVO createReqVO) {
        return success(emissionFactorService.createEmissionFactor(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新碳排放因子")
    @PreAuthorize("@ss.hasPermission('carbon:emission-factor:update')")
    public CommonResult<Boolean> updateEmissionFactor(@Valid @RequestBody EmissionFactorUpdateReqVO updateReqVO) {
        emissionFactorService.updateEmissionFactor(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除碳排放因子")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('carbon:emission-factor:delete')")
    public CommonResult<Boolean> deleteEmissionFactor(@RequestParam("id") Integer id) {
        emissionFactorService.deleteEmissionFactor(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得碳排放因子")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('carbon:emission-factor:query')")
    public CommonResult<EmissionFactorRespVO> getEmissionFactor(@RequestParam("id") Integer id) {
        EmissionFactorDO emissionFactor = emissionFactorService.getEmissionFactor(id);
        EmissionFactorRespVO respVO = EmissionFactorConvert.INSTANCE.convert(emissionFactor);

        if (respVO != null) {
            // 因子数值
            double value = 0D;
            Double upstreamEmissions = respVO.getUpstreamEmissions();
            Double downstreamEmissions = respVO.getDownstreamEmissions();
            if (upstreamEmissions != null) {
                value += upstreamEmissions;
            }
            if (downstreamEmissions != null) {
                value += downstreamEmissions;
            }
            // 因子单位
            String unitLeft = null;
            String unitRight = null;
            if (respVO.getUpstreamEmissionsUnitN() != null) {
                unitLeft = respVO.getUpstreamEmissionsUnitN().replaceAll("\\s+", "");
                unitRight = respVO.getUpstreamEmissionsUnitD().replaceAll("\\s+", "");
            } else if (respVO.getDownstreamEmissionsUnitN() != null) {
                unitLeft = respVO.getDownstreamEmissionsUnitN().replaceAll("\\s+", "");
                unitRight = respVO.getDownstreamEmissionsUnitD().replaceAll("\\s+", "");
            }

            respVO.setName(respVO.getLevel3c())
                    .setValue(value)
                    .setUnitLeft(unitLeft)
                    .setUnitRight(unitRight);
        }
        return success(respVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得碳排放因子分页")
    @PreAuthorize("@ss.hasPermission('carbon:emission-factor:query')")
    public CommonResult<PageResult<EmissionFactorRespVO>> getEmissionFactorPage(@Valid EmissionFactorPageReqVO pageVO) {
        PageResult<EmissionFactorDO> pageResult = emissionFactorService.getEmissionFactorPage(pageVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(new PageResult<>(pageResult.getTotal()));
        }

        List<EmissionFactorRespVO> respList = new ArrayList<>();
        pageResult.getList().forEach(emissionFactorDO -> {
            EmissionFactorRespVO respVO = EmissionFactorConvert.INSTANCE.convert(emissionFactorDO);
            // 因子数值
            double value = 0D;
            Double upstreamEmissions = respVO.getUpstreamEmissions();
            Double downstreamEmissions = respVO.getDownstreamEmissions();
            if (upstreamEmissions != null) {
                value += upstreamEmissions;
            }
            if (downstreamEmissions != null) {
                value += downstreamEmissions;
            }
            // 因子单位
            String unitLeft = null;
            String unitRight = null;
            if (respVO.getUpstreamEmissionsUnitN() != null) {
                unitLeft = respVO.getUpstreamEmissionsUnitN().replaceAll("\\s+", "");
                unitRight = respVO.getUpstreamEmissionsUnitD().replaceAll("\\s+", "");
            } else if (respVO.getDownstreamEmissionsUnitN() != null) {
                unitLeft = respVO.getDownstreamEmissionsUnitN().replaceAll("\\s+", "");
                unitRight = respVO.getDownstreamEmissionsUnitD().replaceAll("\\s+", "");
            }

            respVO.setName(respVO.getLevel3c())
                    .setValue(value)
                    .setUnitLeft(unitLeft)
                    .setUnitRight(unitRight);

            respList.add(respVO);
        });

        return success(new PageResult<>(respList, pageResult.getTotal()));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出碳排放因子 Excel")
    @PreAuthorize("@ss.hasPermission('carbon:emission-factor:export')")
    @OperateLog(type = EXPORT)
    public void exportEmissionFactorExcel(@Valid EmissionFactorExportReqVO exportReqVO,
                                          HttpServletResponse response) throws IOException {
        List<EmissionFactorDO> list = emissionFactorService.getEmissionFactorList(exportReqVO);
        // 导出 Excel
        List<EmissionFactorExcelVO> datas = EmissionFactorConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "碳排放因子.xls", "数据", EmissionFactorExcelVO.class, datas);
    }

}
